from WeChatApi.Api import WechatApi
from Config.ConfigController import ConfigController
import json
from urllib import request
from urllib import parse
from Logger.Logger import Logger

logFile = './Logger/logging.json'
configFile = './Config/config.ini'

#发送上线提醒
def sendOnlineNotice(userID, ipAddr):
	api = WechatApi(configFile=configFile, logFile=logFile)
	nameNode = getOpenIDAndName(userID)
	# print(nameNode)
	data = makeData(userID=userID, ipAddr=ipAddr, name=nameNode['name'])
	api.sendOnLineNotice(userID=userID,
						 openID=nameNode['openid'],
						 data=data)


# 生成模版消息数据
def makeData(userID, ipAddr, name):
	location = getLoginLocation(ipAddr)
	data = {
		"first": {
			"value": "你好，你有一条新的上线消息，敬请查收",
			"color": "#173177"
		},
		"keyword1": {
			"value": userID,
			"color": "#173177"
		},
		"keyword2": {
			"value": name,
			"color": "#173177"
		},
		"keyword3": {
			"value": "有线登陆",
			"color": "#173177"
		},
		"keyword4": {
			"value": "北洋园校区",
			"color": "#173177"
		},
		"keyword5": {
			"value": getRemainUsage(userID=userID),
			"color": "#173177"
		},
		"remark": {
			"value": "如非本人登录，请尽快处理。",
			"color": "#173177"
		}
	}
	if location['wifi'] is True:
		data['keyword3']['value'] = "无线登录"
	if location['new_campus'] is not True:
		data['keyword4']['value'] = "卫津路校区"
	return data


# 根据IP地址映射登录位置
def getLoginLocation(ipAddr="0.0.0.0"):
	location = {
		"wifi": False,
		"new_campus": False
	}
	return location


# 获取剩余流量，访问外部接口
def getRemainUsage(userID):
	config = ConfigController(configFile=configFile, logFile=logFile)
	url = config.getConfig(sectionName='SRUN', optionName='remain_usage') + userID
	httpRequest = request.Request(url)
	httpResponse = request.urlopen(httpRequest)
	responseSource = httpResponse.read().decode('utf-8')
	responseJson = json.loads(responseSource)
	# print(responseJson)
	if responseJson['code'] == "0" and responseJson['message'] == "ok":
		return responseJson['data']
	else:
		logger = Logger(logFile)
		logger.fileInfoLogger.error('获取剩余流量失败，返回数据为：', responseJson)
		return None


# 通过学号获取姓名和openID
def getOpenIDAndName(userID):
	with open("name_list.json", 'r', encoding='utf-8') as json_file:
		namelist = json.load(json_file)
		for nameNode in namelist:
			if nameNode['id'] == userID:
				return {
					"openid": nameNode['openid'],
					"name": nameNode['name']
				}
			else:
				continue


if __name__ == '__main__':
	sendOnlineNotice('3013218097', '0.0.0.0')
